//
//  AppDelegate.swift
//  SinaWeibo
//
//  Created by 李旭阳 on 15/11/8.
//  Copyright © 2015年 apple. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.backgroundColor = UIColor.whiteColor()
        window?.makeKeyAndVisible()
        
        window?.rootViewController = defaultRootController()
        
        //设置主题色
        setThemeColor()
        //注册通知
        registerNotification()
        
        return true
    }
    
    private func setThemeColor(){
        UINavigationBar.appearance().tintColor = themeColor
        UITabBar.appearance().tintColor = themeColor
    }
    
    //MARK: 监听通知
    private func registerNotification() {
        //object  观测某个对象发出的通知 如果为nil  就是观测所有的对象发出的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchToRootVC:", name: AppSwitchRootViewControler, object: nil)
    }
    
    //MARK: 监听通知的方法
    @objc private func switchToRootVC(n: NSNotification) {
        //print(n)
        //跳转到MainVC
        if (n.object as? String ) != nil{
            window?.rootViewController = WelComeViewController()
            return
        }
        window?.rootViewController = MainViewController()
    }
    //MARK: 移除通知
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    //MARK: 检测是否是新版本
    private func isNewVersion() -> Bool{
        //1. 取出当前版本
        let versionStr = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
        let versionNum = Double(versionStr)
        
        //2. 取出沙盒中保存的版本
        let key = "sandBoxKey"
        let userdefaults = NSUserDefaults.standardUserDefaults()
        let lastVersion = userdefaults.doubleForKey(key)
        
        //3. 保存新版本
        userdefaults.setDouble(versionNum!, forKey: key)
        //同步到沙盒
        userdefaults.synchronize()
        
        //4. 比较新旧版本
        return versionNum! > lastVersion
    }
    
    //MARK: 判断用户是否登陆 并且是否是新版本
    private func defaultRootController() -> UIViewController{
        if UserAccountViewModel().userLogin{
            return isNewVersion() ? NewFeatureViewController() : WelComeViewController()
        }
        return MainViewController()
    }
}

